package com.csw.android.dev_utils.utils

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.media.AudioManager
import androidx.lifecycle.MutableLiveData
import com.csw.android.dev_utils.SDK
import kotlin.math.max

object MediaVolumeManager {

    private val audioManager: AudioManager

    var deviceMaxVolume: Int = 0
        private set

    val volume = object : MutableLiveData<Int>() {
        override fun postValue(value: Int) {
            super.postValue(max(0, Integer.min(value, deviceMaxVolume)))
        }

        override fun setValue(value: Int) {
            super.setValue(max(0, Integer.min(value, deviceMaxVolume)))
        }
    }

    init {
        val context = SDK.getApplication()
        audioManager = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager
        deviceMaxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC)
        volume.value = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC)
        val intentFilter = IntentFilter("android.media.VOLUME_CHANGED_ACTION")
        val receiver = object : BroadcastReceiver() {
            override fun onReceive(context: Context?, intent: Intent?) {
                intent?.let {
                    if ("android.media.VOLUME_CHANGED_ACTION" == it.action) {
                        volume.value = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC)
                    }
                }
            }
        }
        context.registerReceiver(receiver, intentFilter)
        volume.observeForever {
            it ?: return@observeForever
            if (it != audioManager.getStreamVolume(AudioManager.STREAM_MUSIC)) {
                audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, it, 0)
            }
        }
    }

}